package com.leyou.item.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.dto.PageDTO;
import com.leyou.common.exception.LyException;
import com.leyou.item.dto.BrandDTO;
import com.leyou.item.entity.Brand;
import com.leyou.item.entity.CategoryBrand;
import com.leyou.item.mapper.BrandMapper;
import com.leyou.item.service.BrandService;
import com.leyou.item.service.CategoryBrandService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;


@Service
public class BrandServiceImpl extends ServiceImpl<BrandMapper, Brand> implements BrandService {

     //分页查询
    @Override
    public PageDTO<BrandDTO> queryByPage(Integer page, Integer rows, String key) {
        //1.构建分页条件
        IPage<Brand> pg = new Page<>(page,rows);
        // 2.判断key是否存在
        boolean condition = StringUtils.isNoneBlank(key);
      //3.分页查询同时包含条件查询
        page(pg,new QueryWrapper<Brand>()
        .like(condition,"name",key)
        .or()
        .eq(condition,"letter",key));
        //根据查询结果，封装分页响应结果,因为返回的是brandDTO集合所以要转换噢噢噢噢噢噢噢噢
        return new PageDTO<>(pg.getTotal(), pg.getPages(), BrandDTO.convertEntityList(pg.getRecords()));
    }
    //添加品牌
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addBrand(BrandDTO brandDTO,List<Long> cids) {
        Brand brand = brandDTO.toEntity(Brand.class);
        boolean save = this.save(brand);
        if(!save){
            throw  new LyException(500,"添加品牌失败");
        }else {
            saveCategoryBrand(cids, brand.getId());
        }
    }
    //把保存中间表的放法抽取出来
    private void saveCategoryBrand(List<Long> cids, Long bid) {
        // 封装中间表对象的集合
        List<CategoryBrand> list = cids.stream()
                .map(cid -> CategoryBrand.of(cid, bid))
                .collect(Collectors.toList());
        // 批量写入中间表数据
        categoryBrandService.saveBatch(list);
    }

    //修改品牌
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateBrand(BrandDTO brandDTO,List<Long> cids) {
        // 1.更新品牌
        boolean success = updateById(brandDTO.toEntity(Brand.class));
        // 2.根据品牌id删除中间表数据
        if(!success) {
            throw new LyException(500,"修改商品失败");
        }else {
            //SQL语句
            categoryBrandService.remove(
                    new QueryWrapper<CategoryBrand>().eq("brand_id", brandDTO.getId()));
        }
        // 3.重新插入中间表数据
        saveCategoryBrand(cids, brandDTO.getId());
    }
    //根据ID集合查询品牌集合
    @Override
    public List<BrandDTO> queryBrandByIds(List<Long> ids) {

        return BrandDTO.convertEntityList(this.listByIds(ids));

    }
    //根据分类ID查询品牌集合
    @Autowired
    private CategoryBrandService categoryBrandService;
    @Override
    public List<BrandDTO> queryBrandByCid(Long cid) {
        List<Long> bids = this.categoryBrandService.query().eq("category_id", cid).list().stream()
                .map(CategoryBrand::getBrandId).collect(Collectors.toList());
        return  queryBrandByIds(bids);
    }
   //根据ID查询品牌集合
    @Override
    public BrandDTO queryBrandById(Long id) {
        Brand byId = this.getById(id);
        return new BrandDTO(byId);
    }
    //删除品牌
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteById(Long id) {
        boolean b = this.removeById(id);
        if(b) {
            //删除中间表
            categoryBrandService.remove(
                    new QueryWrapper<CategoryBrand>().eq("brand_id", id));
        }
    }
}